/**
 * 
 */
package org.wejde.muel;

import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 * @author webbpinner
 *
 */
public class muelLauncher {

	private final static String FILENAME = "/Users/webbpinner/Desktop/interface.xml";
	/**
	 * The main program.  
	 * @param args
	 */
	public static void main(String[] args) {
		
		String filename = "";
		String error = "";
		
		// DEBUG
		//System.err.println("# of arguments: " + args.length);
				
		// Re-define the configuration file if the
		// filename was passed as a command-line argument.
		if (args.length > 0) {
			filename = args[0];
		} else {
			filename = muelLauncher.FILENAME;
		}
		
		// Create and parse the configuration file.
		muelConfigParser config = new muelConfigParser(filename);
		if(!config.isValid()) {
			JOptionPane.showMessageDialog(null, "There is a problem with the configuration file:\n" + filename + "\n\n" + config.getErrorMessage(), "Configuration Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		// DEBUG
		// System.err.println("OS.NAME: " + System.getProperty("os.name").toLowerCase());
		boolean IS_MAC = System.getProperty("os.name").toLowerCase().startsWith("mac os x");
		
		if(IS_MAC) {
			// DEBUG
			//System.err.println("Is Mac");
			System.setProperty("apple.laf.useScreenMenuBar", "true");
			System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Muel");
		}
		
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			System.err.println("Can't set look and feel: " + e);
		}

		// XMPP-based Log client;
		xmppLogClient xmpp = null;

		// Verify XMPP AND UDP logging are NOT enabled.
		if(config.isUDPLogging() && config.isXMPPLogging()) {
			JOptionPane.showMessageDialog(null, "UDP and XMPP logging cannot both be enable.\nPlease disable XMPP or UDP logging.", "Configuration Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		while(true) {
			
			// Build the login window based on the types of logging occurring.
			// These are components related to all types.
		
			// Components related to the Welcome message.
			JLabel label_welcome = new JLabel("Welcome to Muel Version " + muel.VERSION);
			label_welcome.setFont(new Font("SansSerif", Font.PLAIN, 18));
		
			// Components related to "login" field
			JLabel label_loginname = new JLabel("Enter your login name:");
			JTextField loginname = new JTextField(config.getUsername());

			// Components related to the error message.
			JLabel label_error = new JLabel(error);
		
			// Components related to "local logging" field
			JCheckBox checkbox_locallog = new JCheckBox("Local Logging", config.isLocalLogging());
			checkbox_locallog.setEnabled(false);
		
			// If using XMPP logging, prompt for user/pass
			if(config.isXMPPLogging()) {

				// Initialize xmppLogClient object
				xmpp = new xmppLogClient(config.getServerName(), config.getServerPort());

				// Components related to "password" field
				JLabel label_password = new JLabel("Enter your password:");
				JPasswordField password = new JPasswordField(config.getPassword());

				// Components related to server name:port.
				JLabel label_server = new JLabel("Server: " + config.getServerName() + ":" + config.getServerPort());

				// Loop login dialog window for logging into the XMPP server.
				do {
				
					// Build JComponent array
					Object[] array = { label_welcome, label_error, label_loginname, loginname, label_password, password, label_server, checkbox_locallog};
				
					// Build and display the login window 
					int res = JOptionPane.showConfirmDialog(null, array, "XMPP Server Login", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

					// Handle the return value from the dialog box.
					// User hit OK
					if (res == JOptionPane.OK_OPTION) {

						// DEBUG
						//System.err.println("User: " + loginname.getText());
						//System.err.println("Password: " + new String(password.getPassword()));
					
						// Attempt to login
						// If fail, set the error message.
						if(!xmpp.login(loginname.getText(), new String(password.getPassword()))){
							if(!xmpp.isXMPPConnected()){
								error = "<html><FONT COLOR=RED>Error connecting to server.</FONT></html>";
								label_error.setText(error);
							} else if (!xmpp.isXMPPLoggedIn()) {
								error = "<html><FONT COLOR=RED>Error authenticating to server.</FONT></html>";
								label_error.setText(error);
							} else {
								error = "<html><FONT COLOR=RED>Unknown connection Error.</FONT></html>";
								label_error.setText(error);
							}
						} 

						// If success, set the username,
						// password in the configuration object 
						else {
							error = "";
							label_error.setText(error);
							config.setUsername(loginname.getText());
							config.setPassword(new String(password.getPassword()));
						}
					}	
				
					// User hit CANCEL
					else if (res == JOptionPane.CANCEL_OPTION) {
						// Kill the program
						System.exit(0);
					}
					
					// User closed the window without hitting any button
					else if (res == JOptionPane.CLOSED_OPTION) {
						// Kill the program
						System.exit(0);
					}
				
					// Loop until a valid login is provided or the
					// program exits.
				} while (!xmpp.isXMPPLoggedIn());
		
				// If using XMPP logging, prompt for username
			} else if (config.isUDPLogging()) {
			
				JLabel label_server = new JLabel("Server: " + config.getServerName() + ":" + config.getServerPort());
			
				Object[] array = { label_welcome, label_loginname,loginname, label_server, checkbox_locallog };
			
				int res = JOptionPane.showConfirmDialog(null, array, "UDP Server Login",
						JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

				do {
				
					// User hit OK
					if (res == JOptionPane.OK_OPTION) {
						// Set the username
						config.setUsername(loginname.getText());
					}
				
					// User hit CANCEL
					else if (res == JOptionPane.CANCEL_OPTION) {
						System.exit(0);
					}
					
					// User closed the window without hitting any button
					else if (res == JOptionPane.CLOSED_OPTION) {
						System.exit(0);
					}
				} while (config.getUsername().length()==0);
			}
			
		if (!config.isUDPLogging() && !config.isXMPPLogging() && config.isLocalLogging()) {
			
			Object[] array = { label_welcome, label_loginname, loginname, checkbox_locallog };
		
			int res = JOptionPane.showConfirmDialog(null, array, "Local Logging Only",
					JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

			do {
			
				// User hit OK
				if (res == JOptionPane.OK_OPTION) {
					// Set the username
					config.setUsername(loginname.getText());
				}
			
				// User hit CANCEL
				else if (res == JOptionPane.CANCEL_OPTION) {
					System.exit(0);
				}
				
				// User closed the window without hitting any button
				else if (res == JOptionPane.CLOSED_OPTION) {
					System.exit(0);
				}
			} while (config.getUsername().length()==0);
		}
	
			// Build the main program JFrame
			muel frame;
			ExitWindow exit = new ExitWindow();
		
			// Setup muel depending on the type of logging
			// being performed.
			if(xmpp != null) {
				frame = new muel(config, xmpp);
			} else {
				frame = new muel(config, null);
			}
			frame.addWindowListener(exit);
			frame.setVisible(true);
			
			while(frame.isVisible()) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
